﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESSecondaryWarehouseWarehousingForm : ShopfloorPage
{
    const string QueryWhere = "uMESSecondaryWarehouseWarehousingForm";//test 0922
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESSecondaryWarehouseBusiness bll = new uMESSecondaryWarehouseBusiness();
    int m_PageSize = 10;
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：入库操作";
        master.strTitle = "入库操作";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();

        WebPanel = WebAsyncRefreshPanel1;
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { QueryData(upageTurning.CurrentPageIndex); });
        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
        }
    }


    #region 数据查询

    #region 绑定分厂二级库列表
    protected void GetFactoryStock()
    {
          DataTable DT = bll.GetFactoryStockInfo();

        ddlFactoryStock.DataTextField = "FactoryStockName";
        ddlFactoryStock.DataValueField = "FactoryStockID";
        ddlFactoryStock.DataSource = DT;
        ddlFactoryStock.DataBind();

        ddlFactoryStock.Items.Insert(0, "");
    }
    #endregion

    #region 绑定入库原因列表
    protected void GetStockReasonInfo()
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("StockReason", "1");
        DataTable DT = bll.GetStockReasonInfo(para);

        ddlStockReason.DataTextField = "StockReasonName";
        ddlStockReason.DataValueField = "StockReasonId";
        ddlStockReason.DataSource = DT;
        ddlStockReason.DataBind();

        ddlStockReason.Items.Insert(0, "");
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        hdScanCon.Value = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = "";
        txtEndDate.Value = "";
        txtContainerName.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        upageTurning.TotalRowCount = 0;
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(hdScanCon.Value))
        {
            result.Add("ScanContainerName", hdScanCon.Value);
        }
        else
        {
            result.Add("ProcessNo", strProcessNo);
            result.Add("ContainerName", strContainerName);
            result.Add("ProductName", strProductName);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
        }
        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();
        ClearDispData();
        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";
            hdScanCon.Value = string.Empty;
            if (strScan != string.Empty)
            {

                hdScanCon.Value = strScan;
                QueryData(1);
            }
        }
        catch(Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }


    //查询按钮
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {

            hdScanCon.Value = string.Empty;
            QueryData(upageTurning.CurrentPageIndex);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    public void QueryData(int intIndex)
    {
        ClearMessage();

        ClearDispData();
        uMESPagingDataDTO result = bll.GetSourceData(GetQuery(), intIndex, m_PageSize);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtContainerId.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtProductId.Text = string.Empty;
        txtInQty.Text = string.Empty;
        txtAllInQty.Text = "0";
        txtStockQty.Text = "0";
        txtUomId.Text = string.Empty;
        txtQty.Text = string.Empty;
     

        txtEmployeeId.Text = string.Empty;
        txtInEmployee.Text = string.Empty;
        try
        {
            ddlFactoryStock.SelectedIndex = 0;
            ddlStockReason.SelectedIndex = 0;
        }
        catch
        {
        }

        ItemGrid.Clear();
       
    }

    public void ResetQuery()
    {
        ClearMessage();

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        upageTurning.TotalRowCount = 0;
        ItemGrid.Rows.Clear();
    }
    #endregion
    
    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();

        try
        {
            txtDispProcessNo.Text = string.Empty;
            if(e.Row.Cells.FromKey("ProcessNo").Value!=null)
            { 
                string strProcessNo = e.Row.Cells.FromKey("ProcessNo").Value.ToString();
                txtDispProcessNo.Text = strProcessNo;
            }

            txtDispOprNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("OprNo").Value != null)
            {
                string strOprNo = e.Row.Cells.FromKey("OprNo").Value.ToString();
                txtDispOprNo.Text = strOprNo;
            }

            string strContainerName = e.Row.Cells.FromKey("ContainerName").Value.ToString();
            txtDispContainerName.Text = strContainerName;

            string strContainerID = e.Row.Cells.FromKey("ContainerID").Value.ToString();
            txtContainerId.Text = strContainerID;

            string strProductName = e.Row.Cells.FromKey("ProductName").Value.ToString();
            txtDispProductName.Text = strProductName;

            txtDispDescription.Text = string.Empty;
            if (e.Row.Cells.FromKey("Description").Value != null)
            {
                string strDescription = e.Row.Cells.FromKey("Description").Value.ToString();
                txtDispDescription.Text = strDescription;
            }

            txtProductId.Text = string.Empty;
            if (e.Row.Cells.FromKey("productid").Value != null)
            {
                string strProductId = e.Row.Cells.FromKey("productid").Value.ToString();
                txtProductId.Text = strProductId;
            }

            txtUomId.Text = string.Empty;
            if (e.Row.Cells.FromKey("uomid").Value != null)
            {
                string strUomId = e.Row.Cells.FromKey("uomid").Value.ToString();
                txtUomId.Text = strUomId;
            }

            //库存数 
            txtStockQty.Text = "0";
            if (e.Row.Cells.FromKey("StockQty").Value != null)
            {
                string strStockQty = e.Row.Cells.FromKey("StockQty").Value.ToString();
                txtStockQty.Text = strStockQty;
            }

            //批次数量
            string strQty = string.Empty;
            if (e.Row.Cells.FromKey("qty").Value != null)
            {
               strQty  = e.Row.Cells.FromKey("qty").Value.ToString();
                txtQty.Text = strQty;
            }

            //显示交接人
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            txtInEmployee.Text = userInfo["FullName"];
            txtEmployeeId.Text = userInfo["EmployeeID"];

            //分厂二级库帮
            GetFactoryStock();

            //入库原因显示
            GetStockReasonInfo();

            //已入库数量
            string strAllInQty ="0";
             if (e.Row.Cells.FromKey("inqty").Value != null)
            {
                strAllInQty = e.Row.Cells.FromKey("inqty").Value.ToString();
                txtAllInQty.Text = strAllInQty;
            }


            //入库数量 
            if (strQty !="" && strAllInQty!="")
            {
                if (IsNumeric(strQty) == true && IsNumeric(strAllInQty) == true)
                {
                    if (IsInt(strQty) ==true)
                    {
                        txtInQty.Text = (Convert.ToInt32(strQty) - Convert.ToInt32(strAllInQty)).ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            if(CheckData() == false)
            {
                return;
            }
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;

            //以字典形式传递参数
            Dictionary<string, object> para = new Dictionary<string, object>();
            DataSet ds = new DataSet();
            //返回消息信息
            string strMessage = string.Empty;
            //主表要保存的信息
            DataTable dtMain = new DataTable();
            dtMain.Columns.Add("ID");//唯一标识
            dtMain.Columns.Add("ContainerID");//生产批次ID
            dtMain.Columns.Add("FactoryStockID");//二级库ID
            dtMain.Columns.Add("ProductID");//产品 / 图号ID
            dtMain.Columns.Add("Qty");//批次数量
            dtMain.Columns.Add("UOMID");//计量单位ID
            dtMain.Columns.Add("ContainerName");//生产批次号
            dtMain.Columns.Add("ProductName");//产品 / 图号
            dtMain.Columns.Add("Description");//名称
            dtMain.Columns.Add("ProcessNo");//工作令号
            dtMain.Columns.Add("OprNo");//作业令号
            dtMain.Columns.Add("InQty");//入库数量
            dtMain.Columns.Add("OutQty");//出库数量
            dtMain.Columns.Add("InDate");//最后一次入库时间
            dtMain.Columns.Add("StockQty");//库存数

            //子表要保存的信息
            DataTable dtMine = new DataTable();
            dtMine.Columns.Add("ID");//唯一标识
            dtMine.Columns.Add("ContainerID");//生产批次ID
            dtMine.Columns.Add("FactoryStockID");//二级库ID
            dtMine.Columns.Add("StockReasonID");//出/入库原因ID
            dtMine.Columns.Add("ProductID");//产品/图号ID
            dtMine.Columns.Add("Qty");//出/入数量
            dtMine.Columns.Add("UOMID");//计量单位ID
            dtMine.Columns.Add("EmployeeID");//操作者ID
            dtMine.Columns.Add("OprDate");//操作时间
            dtMine.Columns.Add("Type");//类型
            dtMine.Columns.Add("Notes");//备注
            dtMine.Columns.Add("EmployeeName");//操作者

            //查询主表中是否已添加该批次信息，如果未添加则进行添加，已添加则修改相关信息

            para.Add("ContainerId", txtContainerId.Text);
            DataTable dt1 = bll.GetFactoryStockMainInfo(para);
            if (dt1.Rows.Count > 0)
            {
                DataTable dtUpdate = new DataTable();
                dtUpdate.Columns.Add("TableName");
                dtUpdate.Columns.Add("containerid");//
                dtUpdate.Columns.Add("InQty");//入库数量
                dtUpdate.Columns.Add("InDate");//最后一次入库时间
                dtUpdate.Columns.Add("StockQty");//库存数

                dtUpdate.Rows.Add();
                int intUpdateRow = dtUpdate.Rows.Count - 1;
                dtUpdate.Rows[intUpdateRow]["TableName"] = "StockInfo";
                dtUpdate.Rows[intUpdateRow]["containerid"] = txtContainerId.Text + "㊣String";
                dtUpdate.Rows[intUpdateRow]["InQty"] = (Convert.ToInt32(txtAllInQty.Text) + Convert.ToInt32(txtInQty.Text)).ToString() + "㊣String";//入库数量
                dtUpdate.Rows[intUpdateRow]["InDate"] = DateTime.Now + "㊣Date";//最后一次入库时间
                dtUpdate.Rows[intUpdateRow]["StockQty"] = (Convert.ToInt32(txtStockQty.Text) + Convert.ToInt32(txtInQty.Text)).ToString() + "㊣String";//入库数量


                int iResult = bll.UpdateDataToDatabase(dtUpdate,out strMessage);
                if (iResult == -1)
                {
                    DisplayMessage(strMessage, false);
                    return;
                }
            }
            else
            {
                dtMain.Rows.Add();
                int intMainRow = dtMain.Rows.Count - 1;
                dtMain.Rows[intMainRow]["ID"]= DateTime.Now.ToString("yyyyMMddHHmmssffff") + "㊣String"; //唯一标识
                dtMain.Rows[intMainRow]["ContainerID"]= txtContainerId.Text + "㊣String";//生产批次ID
                dtMain.Rows[intMainRow]["FactoryStockID"] = ddlFactoryStock.SelectedValue + "㊣String";//二级库ID
                dtMain.Rows[intMainRow]["ProductID"] = txtProductId.Text + "㊣String";//产品 / 图号ID
                dtMain.Rows[intMainRow]["Qty"]= txtQty.Text + "㊣Integer";//批次数量
                dtMain.Rows[intMainRow]["UOMID"]=txtUomId.Text + "㊣String";//计量单位ID
                dtMain.Rows[intMainRow]["ContainerName"]=txtDispContainerName.Text + "㊣String";//生产批次号
                dtMain.Rows[intMainRow]["ProductName"]=txtDispProductName.Text + "㊣String";//产品 / 图号
                dtMain.Rows[intMainRow]["Description"] =txtDispDescription.Text + "㊣String";//名称
                dtMain.Rows[intMainRow]["ProcessNo"] = txtDispProcessNo.Text + "㊣String";//工作令号
                dtMain.Rows[intMainRow]["OprNo"] = txtDispOprNo.Text + "㊣String";//作业令号
                dtMain.Rows[intMainRow]["InQty"] = (Convert.ToInt32(txtAllInQty.Text) + Convert.ToInt32(txtInQty.Text)).ToString() + "㊣Integer";//入库数量
                dtMain.Rows[intMainRow]["OutQty"]="0" + "㊣Integer";//出库数量
                dtMain.Rows[intMainRow]["InDate"]= DateTime.Now + "㊣Date";//最后一次入库时间
                dtMain.Rows[intMainRow]["StockQty"] = (Convert.ToInt32(txtStockQty.Text) + Convert.ToInt32(txtInQty.Text)).ToString() + "㊣Integer";//库存数量


                ds.Tables.Add(dtMain);
                ds.Tables[0].TableName = "StockInfo" ;

            }

            dtMine.Rows.Add();
            int intMineRow = dtMine.Rows.Count - 1;
            dtMine.Rows[intMineRow]["ID"] = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "㊣String"; //唯一标识
            dtMine.Rows[intMineRow]["ContainerID"] = txtContainerId.Text + "㊣String";//生产批次ID
            dtMine.Rows[intMineRow]["FactoryStockID"] = ddlFactoryStock.SelectedValue + "㊣String";//二级库ID
            dtMine.Rows[intMineRow]["StockReasonID"] = ddlStockReason.SelectedValue + "㊣String";//二级库ID
            dtMine.Rows[intMineRow]["ProductID"] = txtProductId.Text + "㊣String";//产品 / 图号ID
            dtMine.Rows[intMineRow]["Qty"] = txtInQty.Text + "㊣Integer";//批次数量
            dtMine.Rows[intMineRow]["UOMID"] = txtUomId.Text + "㊣String";//计量单位ID
            dtMine.Rows[intMineRow]["EmployeeID"] = userInfo["EmployeeID"] + "㊣String";//操作者ID
            dtMine.Rows[intMineRow]["EmployeeName"] = userInfo["FullName"] + "㊣String";//操作者
            dtMine.Rows[intMineRow]["OprDate"] = DateTime.Now + "㊣Date";//操作时间
            dtMine.Rows[intMineRow]["Type"] = "1" + "㊣Integer";//1=入库 2=出库 3=冲账入库 4=冲账出库 
            dtMine.Rows[intMineRow]["Notes"] = "" + "㊣String";//备注

            ds.Tables.Add(dtMine);
            ds.Tables[ds.Tables.Count-1].TableName = "StockHistoryInfo" ;

            para.Add("dsData", ds);

            //保存数据
  
            bool result = bll.SaveDataToDatabase(para,out strMessage);
            if (result == true)
            {
                ClearDispData();
            }
            
            DisplayMessage(strMessage, result);
          

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 数据验证
    protected Boolean CheckData()
    {
        Boolean result = true;

        if (txtDispContainerName.Text=="")
        {
            DisplayMessage("请选择入库信息！", false);
            result = false;
            return result;
        }

        if (ddlFactoryStock.SelectedIndex==0)
        {
            DisplayMessage("请选择分厂二级库！", false);
            result = false;
            return result;
        }

        if (ddlStockReason.SelectedIndex == 0)
        {
            DisplayMessage("请选择入库原因！", false);
            result = false;
            return result;
        }

         //入库数量 
        string strInQty = txtInQty.Text;
        if (strInQty != "")
        {
            if (IsNumeric(strInQty) == true)
            {
                if (IsInt(strInQty) == false)
                {
                    DisplayMessage("入库数量必须为正整数！", false);
                    result = false;
                    return result;
                }
            }
            else
            {
                DisplayMessage("入库数量必须为数字！", false);
                result = false;
                return result;
            }
        }
        else
        {
            DisplayMessage("请输入入库数量！", false);
            result = false;
            return result;
        }
        //批次数量
        string strQty = txtQty.Text;

        //已入库数量
        string strAllInQty = txtAllInQty.Text;

        if (Convert.ToInt32(strQty) < Convert.ToInt32(strAllInQty) + Convert.ToInt32(strInQty))
        {
            DisplayMessage("入库总数量需小于批次数量！", false);
            result = false;
            return result;
        }

        return result;
    }
    #endregion

    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    #endregion

}